from multiprocessing import Pool
from mitmproxy import ctx, flow, http
import json, time, os
import chardet
import logging

# 拦截器
# 拦截请求和响应，并修改请求和响应的内容
# 修改请求参数
# 修改返回参数
# 保存接口返回数据
# 优化：
# 1. 自动检测编码
# 2. 优化代码结构
# 3. 优化日志记录
# 4. 优化文件保存路径
# 5. 优化文件名
# 6. 优化文件内容
# 7. 优化文件写入方式
# 8. 优化文件读取方式
# 9. 优化文件读取方式

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# 获取当前文件的绝对路径
current_file_path = os.path.abspath(__file__)
# 获取项目根目录
project_root = os.path.dirname(os.path.dirname(current_file_path))
# 设置全局变量
global cloudphone_lists

# def request(flow: http.HTTPFlow)->None:
# 	if flow.request.host == "starnews.2345.com":
# 		ctx.log.warn(flow.request.url)

# 修改请求参数  没优化之前
# def request(flow: http.HTTPFlow)->None:
# 	if "starnews.2345.com/v1/apiNews/" in flow.request.url:
# 		#修改固定参数使得推荐接口请求百度数据
# 		params = flow.request.content.decode('gbk').split('&')
# 		for i in range(len(params)):
# 			if 'commonUid' in params[i]:
# 				params[i] = "commonUid=861889044875011"
# 		params = '&'.join(params)
# 		flow.request.content = 	params.encode('gbk')
# 		print(flow.request.content)

# 修改请求参数  优化之后
def request(flow: http.HTTPFlow) -> None:
    if "uphone-test.wo-adv.cn/bucp/servers/resource/" in flow.request.url:
        # 检查请求方法
        if flow.request.method == "POST":
            try:
                # 检查请求内容是否为空
                if not flow.request.content:
                    logger.warning("Request content is empty. Skipping modification.")
                    return
                # 自动检测编码
                detected_encoding = chardet.detect(flow.request.content).get('encoding')
                if not detected_encoding:
                    logger.warning("Encoding detection failed. Using default encoding utf-8.")
                    detected_encoding = 'utf-8'
                content = flow.request.content.decode(detected_encoding)
                params = content.split('&')
                for i in range(len(params)):
                    if 'commonUid' in params[i]:
                        params[i] = "commonUid=861889044875011"
                new_content = '&'.join(params)
                flow.request.content = new_content.encode(detected_encoding)
                logger.info(f"Modified request content: {new_content}")
            except Exception as e:
                logger.error(f"Error modifying POST request: {e}")
        elif flow.request.method == "GET":
            try:
                # 处理 URL 参数
                query_params = dict(flow.request.query)
                if 'commonUid' in query_params:
                    query_params['commonUid'] = "861889044875011"
                flow.request.query = query_params
                logger.info(f"Modified query parameters: {query_params}")
            except Exception as e:
                logger.error(f"Error modifying GET request: {e}")


# 修改返回参数
# def response(flow: http.HTTPFlow)->None:
# 	save(flow,"https://starnews.2345.com/v1/apiTask/getTaskList","./interface/response/tasklist.json")
# 	save(flow,"https://starnews.2345.com/v1/apiTask/finishTask","./interface/response/finish.json")
# 	if "starnews.2345.com/v1/apiNews/" in flow.request.url:
# 		print(flow.response.get_text())
# 		response_content = json.loads(flow.response.get_text())
# 		try:
# 			response_content["data"]["newsList"]["adIds"]=[]
# 			response_content["data"]["topNews"]["data"]=[]
# 		except:
# 			pass
#
# 		flow.response.set_text(json.dumps(response_content))

# 修改返回参数 优化之后
def response(flow: http.HTTPFlow) -> None:
    # 保存特定接口的响应数据
    save(flow, "https://uphone-test.wo-adv.cn/bucp/servers/resource/instance/list", project_root+"/interface/response/phonelist.json")
    save(flow, "https://starnews.2345.com/v1/apiTask/finishTask", "./interface/response/finish.json")
    # 修改 starnews.2345.com/v1/apiNews/ 接口的响应内容
    if "uphone-test.wo-adv.cn/bucp/servers/resource/" in flow.request.url:
        try:
            response_content = flow.response.get_text()
            logger.info(f"Original response content: {response_content}")
            response_data = json.loads(response_content)

            # 修改响应内容
            # if "data" in response_data:
            #     if "newsList" in response_data["data"]:
            #         response_data["data"]["newsList"]["adIds"] = []
            #     if "topNews" in response_data["data"]:
            #         response_data["data"]["topNews"]["data"] = []

            cloudphone_lists= [row['id'] for row in response_data['rows']]

            new_response_content = json.dumps(response_data, ensure_ascii=False, indent=4)
            flow.response.set_text(new_response_content)
            logger.info(f"Modified response content: {new_response_content}")
        except Exception as e:
            logger.error(f"Error modifying response: {e}")


# 保存接口返回数据
# def save(flow, url, file):
#     if flow.request.url == url:
#         response_content = flow.response.get_text()
#         a = json.loads(response_content)
#         a["id"] = int(time.time())
#         with open(file, 'w') as f:
#             json.dump(a, f)

# 保存接口返回数据 优化后
def save(flow: http.HTTPFlow, url: str, file: str) -> None:
    if flow.request.url == url:
        try:
            response_content = flow.response.get_text()
            response_data = json.loads(response_content)
            response_data["id"] = int(time.time())

            # 确保文件路径存在
            os.makedirs(os.path.dirname(file), exist_ok=True)

            with open(file, 'w', encoding='utf-8') as f:
                json.dump(response_data, f, ensure_ascii=False, indent=4)
            logger.info(f"Saved response to {file}")
        except Exception as e:
            logger.error(f"Error saving response to {file}: {e}")
